<template>
  <div id="app">
    <div class="page-loader" ref="loader">
      <div class="page-loader__spinner">
        <svg viewBox="25 25 50 50">
          <circle cx="50" cy="50" r="20" fill="none" stroke-width="2" stroke-miterlimit="10"/>
        </svg>
      </div>
    </div>

    <div role="alert" class="el-notification left" style="top: 150px; z-index: 2000;">
      <i class="el-notification__icon el-icon-success"></i>
      <div class="el-notification__group is-with-icon">
        <h2 class="el-notification__title">系统信息</h2>
        <div class="el-notification__content">
          <p>
            在线用户： {{online}}
              <br>
            <el-button @click="logout" style="float: right" size="mini" type="danger" plain>注销</el-button>
          </p>
        </div>
      </div>
    </div>

    <div class="sidebar">
      <div class="card">
        <header>
          <img class="avatar" width="40" height="40" :alt="user.name" :src="user.avatar">
          <p class="name">{{user.name}}</p>
        </header>
        <footer>
          <input class="search" type="text" placeholder="search user...">
        </footer>
      </div>
      <div class="list">
        <ul>
          <li :class="{ active: current_window_id === 0 }" @click="selectWindow(0)">
            <img class="avatar" width="30" height="30" src="/avatar/group.png">
            <p class="name">官方群组</p>
          </li>
          <li v-for="item in userList" v-if="item.id != form.id" :class="{ active: current_window_id === item.id }"
              @click="selectWindow(item.id)">
            <img class="avatar" width="30" height="30" :alt="item.name" :src="item.avatar">
            <p class="name">{{item.name}}</p>
          </li>
        </ul>
      </div>
    </div>
    <div class="main">
      <div class="message" ref="box">
        <ul>
          <li v-for="(item,key) in messageList" :id="key == (messageList.length - 1) ? 'end' : ''">
            <p class="time">
              <span>{{item.time}}</span>
            </p>
            <div :class="'main ' +  (item.from.id == form.id ? 'self': '')">
              <img class="avatar" width="30" height="30" :src="item.from.avatar"/>
              <span class="main-name">{{item.from.name}}</span>
              <div class="text">{{item.message}}</div>
            </div>
          </li>
        </ul>
      </div>
      <div class="text">
        <el-input
            v-model="form.message" @keyup.native.enter="send"
            type="textarea" :rows="5" placeholder="请输入内容，按 Enter 键发送">
        </el-input>
        <div class="btn">
          <el-button @click="clean" size="mini" type="danger">清空</el-button>
          <el-button @click="send" size="mini" icon="el-icon-position" type="success">发送</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "chat",
  data() {
    return {
      online: 0,
      websocket: undefined,
      user: {
        id: '',
        avatar: '',
        name: ''
      },

      form: {message: ''},

      //当前激活窗口ID
      current_window_id: 0,

      //在线用户列表
      userList: [],
      //推送消息列表
      messageList  : [],

    }
  },
  updated() {
    this.scroll()
  },
  mounted() {
    this.init();
    this.$refs.loader.style.display = 'none';
  },
  created() {
    this.form.id = this.subURL();
    this.formid();
  },
  methods: {

    formid(){
      this.user.id = sessionStorage.getItem("form.id");
      console.log(this.user.id)
    },


    _message(message, type) {
      this.$message({
        message: message,
        type: type
      })
    },
    _notify(title, message, type) {
      this.$notify({
        title: title,
        message: message,
        type: type
      });
    },

    /**
     * Get Rest URL params
     * for example: http://localhost:8080/1560490905528/chat
     *
     * return 1560490905528
     */
    subURL() {
      return window.location.pathname.substring(window.location.pathname.indexOf('/') + 1, window.location.pathname.lastIndexOf('/'))
    },

    init() {
      console.log(this.messageList)
      /**
       * 加载用户信息
       */
      this.initUser();

      /**
       * 加载公共消息列表 -- 群组
       */
      this.initCommonMessage();

      /**
       * 每次刷新页面，主动链接WebSocket
       */
      this.initWebSocket();
    },

    initUser() {
      //加载当前用户信息
      this.$http.get("/chat-service/chat/"+this.user.id).then(response => {
        console.log(response.data.data);
        this.user = response.data.data
      })

      //加载在线用户列表
      this.$http.get("/chat-service/chat/online/list").then(response => {
        let data = response.data.data;
        if (data.length > 0) {
          this.userList = data;
          this.online = this.userList.length
        }
      })
    },

    initWebSocket() {
      let $this = this;
      this.websocket = new WebSocket("ws://localhost:7000/chat-service/chat/"+this.user.id)
      //链接发送错误时调用
      this.websocket.onerror = function () {
        $this._notify('提醒', 'WebSocket链接错误', 'error')
      }
      //链接成功时调用
      this.websocket.onopen = function () {
        $this._notify('提醒', 'WebSocket链接成功', 'success')
      }
      //接收到消息时回调
      this.websocket.onmessage = function (event) {
        $this.clean()
        let entity = JSON.parse(event.data);

        //上线提醒
        if (entity.data == undefined) {
          $this.initUser()
          $this._notify('消息', entity.msg, 'info')
          $this.scroll()
          return;
        }

        //消息接收
        let data = JSON.parse(event.data).data
        if (data.to != undefined) {
          //单个窗口发送，仅推送到指定的窗口
          if (data.from.id == $this.current_window_id) {
            $this.messageList.push(data)
          }
        } else {
          //群发，推送到官方群组窗口
          $this.messageList.push(data)
        }
        $this.scroll()
      }
      //链接关闭时调用
      this.websocket.onclose = function () {
        $this._notify('提醒', 'WebSocket链接关闭', 'info')
      }
    },

    initCommonMessage() {
      this.$http.get("/chat-service/chat/common").then(response => {
        let data = response.data.data
        if (data.length > 0) {
          this.messageList = data
        }
      })
    },

    initSelfMessage() {
      this.$http.get("/chat-service/chat/self/"+this.user.id+ "/"+this.current_window_id).then(response => {
        let data = response.data.data
        this.messageList = data
      })
    },

    //推送消息
    send() {
      if (this.form.message == null || this.form.message.trim() == '') {
        this._message('请输入消息内容', 'warning')
        return;
      }
      if (!this.current_window_id) {
        this.websocket.send(this.form.message.replace(/[\r\n]/g,""))
        this.initCommonMessage()
      } else {
        let message = {
          message: this.form.message,
          from: this.user
        }
        console.log(JSON.stringify(message))
        this.$http.post("/chat-service/chat/push/"+this.current_window_id, message).then(response => {
          if (response.data.code == 200) {
            this.initSelfMessage()
            this.clean()
            this._notify('提醒', '消息推送成功', 'success')
          } else {
            this._notify('提醒', response.data.msg, 'error')
          }
        })
      }
      this.scroll()
    },

    //清空消息
    clean() {
      this.form.message = ''
    },

    //注销
    logout() {
      this.$http.delete("/chat-service/chat/"+this.user.id).then(response => {
        this.websocket.close()
        /*window.location.href = "/"*/
        console.log("11111111")
        this.$router.push({ path: "/Custom/custom_index" });
      })
    },

    //切换选择窗口
    selectWindow(id) {
      this.current_window_id = id;
      if (!this.current_window_id) {
        this.initCommonMessage();
      } else {
        this.initSelfMessage();
      }
    },

    //窗口滚动
    scroll() {
      let box = this.$refs.box
      box.scrollTop = 10000000
    },
  }
}
</script>

<style scoped>
body{
  margin: 0;
  padding: 0;
  height: 100%;
}
#app {
  margin: 120px auto;
  width: 800px;
  height: 600px;
  overflow: hidden;
  border-radius: 3px; }
#app .sidebar, #app .main {
  height: 100%; }
#app .sidebar {
  float: left;
  width: 200px;
  color: #f4f4f4;
  background-color: #2e3238; }
#app .sidebar .list {
  overflow-y: scroll;
  height: 100%;
}
#app .main {
  position: relative;
  overflow: hidden;
  background-color: #eee; }
#app .text {
/*  position: absolute;
  width: 50%;*/
  bottom: 0;
  left: 0; }
#app .message {
  height: calc(100% - 182px); }

.list ul {
  margin: 0;
  padding: 0; }
.list li {
  list-style: none;
  padding: 12px 15px;
  border-bottom: 1px solid #292C33;
  cursor: pointer;
  transition: background-color .1s; }
.list li:hover {
  background-color: rgba(255, 255, 255, 0.03); }
.list li.active {
  background-color: rgba(255, 255, 255, 0.1); }
.list .avatar, .list .name {
  vertical-align: middle; }
.list .avatar {
  border-radius: 2px; }
.list .name {
  display: inline-block;
  margin: 0 0 0 15px; }

.card {
  padding: 12px;
  border-bottom: solid 1px #24272C; }
.card footer {
  margin-top: 10px; }
.card .avatar, .card .name {
  vertical-align: middle; }
.card .avatar {
  border-radius: 2px; }
.card .name {
  display: inline-block;
  margin: 0 0 0 15px;
  font-size: 16px; }
.card .search {
  padding: 0 10px;
  width: 100%;
  font-size: 12px;
  color: #fff;
  height: 30px;
  line-height: 30px;
  border: solid 1px #3a3a3a;
  border-radius: 4px;
  outline: none;
  background-color: #26292E; }

.message {
  padding: 10px 15px;
  overflow-y: scroll; }
.message ul {
  margin-left: -40px; }
.message li {
  list-style: none;
  margin-bottom: 15px; }
.message .time {
  margin: 7px 0;
  text-align: center; }
.message .time > span {
  display: inline-block;
  padding: 0 18px;
  font-size: 12px;
  color: #fff;
  border-radius: 2px;
  background-color: #dcdcdc; }
.message .avatar {
  float: left;
  margin: 0 10px 0 0;
  border-radius: 3px; }
.message .main-name {
  font-size: 11px;
  color: gray;
  display: inherit;
  font-weight: 500;
  margin-bottom: 5px; }
.message .text {
  height: auto !important;
  display: inline-block;
  position: relative;
  padding: 0 10px;
  max-width: calc(100% - 40px);
  min-height: 30px;
  line-height: 2.5;
  font-size: 12px;
  text-align: left;
  word-break: break-all;
  background-color: #fafafa;
  border-radius: 4px; }
.message .text:before {
  content: " ";
  position: absolute;
  top: 9px;
  right: 100%;
  border: 6px solid transparent;
  border-right-color: #fafafa; }
.message .self {
  text-align: right; }
.message .self .avatar {
  float: right;
  margin: 0 0 0 10px; }
.message .self .text {
  background-color: #b2e281; }
.message .self .text:before {
  right: inherit;
  left: 100%;
  border-right-color: transparent;
  border-left-color: #b2e281; }

.text {
  border: 1px solid #e6ebf5;
  height: 160px;
  background: white;
  border-top: solid 1px #ddd; }
.text textarea {
  padding: 10px;
  height: 66%;
  width: 100%;
  border: none;
  outline: none;
  font-family: "Micrsofot Yahei";
  resize: none; }
.text .btn {
  float: right;
  margin: 3px 9px; }
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.el-upload img {
  width: 178px;
  height: 178px;
  display: block;
}

.default_avatars_list {
  display: inline-block;
}
.row {
  margin-top: 15px;
  margin-bottom: 15px;
  margin-right: -15px;
  flex-wrap: wrap;
  margin-left: -15px;
}
.default_avatars_list img {
  width: 11.3%;
  display: inline;
  margin: 1rem;
  border-radius: 3px;
  cursor: pointer;
}
.page-loader {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background-color: #f3f3f3;
  z-index: 999999999;
  align-items: center;
  justify-content: center;
  display: flex;
}

.page-loader__spinner {
  position: relative;
  width: 50px;
  height: 50px;
}
.page-loader__spinner svg {
  animation: rotate 2s linear infinite;
  transform-origin: center center;
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}
.page-loader__spinner svg circle {
  stroke-dasharray: 1, 200;
  stroke-dashoffset: 0;
  animation: dash 1.5s ease-in-out infinite, color 6s ease-in-out infinite;
  stroke-linecap: round;
}
@keyframes dash {
  0% {
    stroke-dasharray: 1, 200;
    stroke-dashoffset: 0;
  }
  50% {
    stroke-dasharray: 89, 200;
    stroke-dashoffset: -35px;
  }
  100% {
    stroke-dasharray: 89, 200;
    stroke-dashoffset: -124px;
  }
}
@keyframes color {
  100%,
  0% {
    stroke: #ff5652;
  }
  40% {
    stroke: #2196F3;
  }
  66% {
    stroke: #32c787;
  }
  80%,
  90% {
    stroke: #ffc107;
  }
}
/*# sourceMappingURL=main.css.map */

</style>
